package ocean.chinacraft.common.entity.fly.control;

import net.minecraft.entity.MobEntity;
import net.minecraft.entity.ai.controller.MovementController;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector3d;

/**
 * 默认飞行控制器
 *
 * @author zhang
 * @since 2021/12/31
 */
public class FlyingControl<T extends MobEntity> extends MovementController {

    private int floatDuration;
    private final T mobEntity;

    public FlyingControl(T mobEntity) {
        super(mobEntity);
        this.mobEntity = mobEntity;
    }

    @Override
    public void tick() {
        if (this.operation == MovementController.Action.MOVE_TO) {
            if (this.floatDuration-- <= 0) {
                this.floatDuration += this.mobEntity.getRandom().nextInt(5) + 2;
                Vector3d vector3d = new Vector3d(this.wantedX - this.mobEntity.getX(),
                        this.wantedY - this.mobEntity.getY(),
                        this.wantedZ - this.mobEntity.getZ());
                double d0 = vector3d.length();
                vector3d = vector3d.normalize();
                if (this.canReach(vector3d, MathHelper.ceil(d0))) {
                    this.mobEntity.setDeltaMovement(this.mobEntity.getDeltaMovement().add(vector3d.scale(0.1D)));
                } else {
                    this.operation = MovementController.Action.WAIT;
                }
            }

        }
    }

    private boolean canReach(Vector3d vector3d, int count) {
        AxisAlignedBB axisalignedbb = this.mobEntity.getBoundingBox();
        for (int i = 1; i < count; ++i) {
            axisalignedbb = axisalignedbb.move(vector3d);
            if (!this.mobEntity.level.noCollision(this.mobEntity, axisalignedbb)) {
                return false;
            }
        }
        return true;
    }
}
